<?php
namespace app\api\controller;
use think\Controller;
use think\Db;

class Article extends Common {
    public function create_article()
    {
        $data = $this->params;
        $data['create_time'] = date("Y-m-d H:i:s",time());
        $data['update_time'] = date("Y-m-d H:i:s",time());
        $data['pv'] = 0;
        $data['status'] = 2;
        $res = db('articles')->insert($data);
        if ($res === false) {
            $this->return_msg(400, '创建失败!');
        } else {
            $this->return_msg(200, '创建成功!');
        }
    }

    // 获取文章列表
    public function get_articles()
    {
        $data = $this->params;
        //获取用户设备数量
        $count = db('articles')->where('title','like',"%".$data['title']."%")
        ->where('status',$data['status'])->count();
        
        $page_num = ceil($count / $data['pageSize']);
        $articles_data['page_num'] = $page_num;
        $articles_data['total'] = $count;
        $articles_data['current_page'] = (int)$data['page'];
        $articles_data['pageSize'] = (int)$data['pageSize'];

        $articles_data['data'] = db('articles')
        ->where('title','like',"%".$data['title']."%")
        ->where('status',$data['status'])
        ->alias('item')
        ->join(['ms_categories'=>'cate'],'item.category_id=cate.id')
        ->field('item.id,item.pv, item.status, item.title,item.description, item.cover, item.create_time, item.update_time, item.category_id, cate.category_name,cate.category_cover')
        ->page($data['page'])
        ->limit($data['pageSize'])
        ->select();

        if ($articles_data === false) {
            $this->return_msg(400, '查询失败!');
        } elseif (empty($articles_data)) {
            $this->return_msg(200, '暂无数据!');
        } else {
            $this->return_msg(200, '获取成功!', $articles_data);
        }
    }

    // 获取文章详情
    public function get_article_detail()
    {
        $data = $this->params;
        $db_res = db('articles')
        ->where('id', $data['article_id'])
        ->find();
        if ($db_res === false) {
            $this->return_msg(400, '查询失败!');
        } elseif (empty($db_res)) {
            $this->return_msg(200, '暂无数据!');
        } else {
            $this->return_msg(200, '获取成功!', $db_res);
        }
    }
}